package com.project.web.wechat.controller.app.cpWeChat;

import com.project.common.core.utils.exception.Result;
import com.project.web.config.WxCorp.WxCpConfig;
import com.project.web.config.WxCorp.WxCpConfiguration;
import com.project.web.util.exception.WeChatCustomException;
import com.project.web.wechat.controller.common.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.api.WxCpTagService;
import me.chanjar.weixin.cp.bean.WxCpTag;
import me.chanjar.weixin.cp.bean.WxCpTagAddOrRemoveUsersResult;
import me.chanjar.weixin.cp.bean.WxCpUser;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 标签管理接口
 *
 * @author wyy
 * @date 2020-06-24
 */
@Api(tags = "标签管理接口")
@RestController("workWxTagController")
@RequestMapping("/weChat/auth/workWx/tag")
public class WorkWxTagController extends BaseController {

    /**
     * 创建标签，返回标签ID
     *
     * @return
     */
    @ApiOperation("创建标签，返回标签ID")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "tagName", value = "标签名称", required = true, dataType = "String")
    })
    @PostMapping(value = "/create")
    public Result<String> create(String tagName, HttpServletRequest request) {
        // 企业微信基本参数
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
        WxCpTagService tagService = wxCpService.getTagService();
        try {
            String tagId = tagService.create(tagName,1);
            return getResult(tagId);
        } catch (WxErrorException e) {
            log.error("创建标签出错：{}", ExceptionUtils.getStackTrace(e));
            throw new WeChatCustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
        }
    }

    /**
     * 更新标签
     *
     * @param tagId   标签ID
     * @param tagName 标签名称
     * @return
     */
    @ApiOperation("更新标签")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "tagId", value = "标签ID", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "tagName", value = "标签名称", required = true, dataType = "String")
    })
    @PostMapping(value = "/update")
    public Result<String> update(String tagId, String tagName, HttpServletRequest request) {

        // 企业微信基本参数
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
        WxCpTagService tagService = wxCpService.getTagService();
        try {
            tagService.update(tagId, tagName);
            return getResult("success");
        } catch (WxErrorException e) {
            log.error("更新标签出错：{}", ExceptionUtils.getStackTrace(e));
            throw new WeChatCustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
        }
    }

    /**
     * 删除标签
     *
     * @param tagId 标签ID
     * @return
     */
    @ApiOperation("删除标签")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "tagId", value = "标签ID", required = true, dataType = "String")
    })
    @GetMapping(value = "/delete")
    public Result<String> delete(String tagId, HttpServletRequest request) {

        // 企业微信基本参数
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
        WxCpTagService tagService = wxCpService.getTagService();
        try {
            tagService.delete(tagId);
            return getResult("success");
        } catch (WxErrorException e) {
            log.error("删除标签出错：{}", ExceptionUtils.getStackTrace(e));
            throw new WeChatCustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
        }
    }

    /**
     * 获取标签列表
     *
     * @return
     */
    @ApiOperation("获取标签列表")
    @GetMapping(value = "/list")
    public Result<List<WxCpTag>> list(HttpServletRequest request) {

        // 企业微信基本参数
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
        WxCpTagService tagService = wxCpService.getTagService();
        try {
            List<WxCpTag> wxCpTags = tagService.listAll();
            return getResult(wxCpTags);
        } catch (WxErrorException e) {
            log.error("获取标签列表出错：{}", ExceptionUtils.getStackTrace(e));
            throw new WeChatCustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
        }
    }

    /**
     * 获取标签成员
     *
     * @param tagId 标签ID
     * @return
     */
    @ApiOperation("获取标签成员")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "tagId", value = "标签ID", required = true, dataType = "String")
    })
    @GetMapping(value = "/listUsersByTagId")
    public Result<List<WxCpUser>> listUsersByTagId(String tagId, HttpServletRequest request) {

        // 企业微信基本参数
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
        WxCpTagService tagService = wxCpService.getTagService();
        try {
            List<WxCpUser> wxCpUsers = tagService.listUsersByTagId(tagId);
            return getResult(wxCpUsers);
        } catch (WxErrorException e) {
            log.error("获取标签成员出错：{}", ExceptionUtils.getStackTrace(e));
            throw new WeChatCustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
        }
    }

    /**
     * 增加标签成员
     *
     * @param tagId    标签ID
     * @param userIds  用户ID集合
     * @param partyIds 部门ID集合
     * @return
     */
    @ApiOperation("增加标签成员")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "tagId", value = "标签ID", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "userIds", value = "用户ID集合", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "partyIds", value = "部门ID集合", required = true, dataType = "String")
    })
    @PostMapping(value = "/addTagUsers")
    public Result<WxCpTagAddOrRemoveUsersResult> addTagUsers(String tagId, List<String> userIds, List<String> partyIds, HttpServletRequest request) {
        // 企业微信基本参数
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
        WxCpTagService tagService = wxCpService.getTagService();
        try {
            WxCpTagAddOrRemoveUsersResult removeUsersResult = tagService.addUsers2Tag(tagId, userIds, partyIds);
            return getResult(removeUsersResult);
        } catch (WxErrorException e) {
            log.error("增加标签成员出错：{}", ExceptionUtils.getStackTrace(e));
            throw new WeChatCustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
        }
    }

    /**
     * 删除标签成员
     *
     * @param tagId 标签ID
     * @return
     */
    @ApiOperation("增加标签成员")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "tagId", value = "标签ID", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "userIds", value = "用户ID集合", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "partyIds", value = "部门ID集合", required = true, dataType = "String")
    })
    @PostMapping(value = "/delTagUsers")
    public Result<WxCpTagAddOrRemoveUsersResult> delTagUsers(String tagId, List<String> userIds, List<String> partyIds, HttpServletRequest request) {

        // 企业微信基本参数
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
        WxCpTagService tagService = wxCpService.getTagService();
        try {
            WxCpTagAddOrRemoveUsersResult removeUsersResult = tagService.removeUsersFromTag(tagId, userIds, partyIds);
            return getResult(removeUsersResult);
        } catch (WxErrorException e) {
            log.error("删除标签成员出错：{}", ExceptionUtils.getStackTrace(e));
            throw new WeChatCustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
        }
    }
}
